package 树;

import 简单.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 树的层次遍历 {

    public static void main(String[] args) {
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode7 = new TreeNode(7);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode8 = new TreeNode(8);
        treeNode5.left = treeNode3;
        treeNode5.right = treeNode7;
        treeNode3.left = treeNode2;
        //treeNode3.right = treeNode4;
        treeNode7.left = treeNode6;
        //treeNode7.right = treeNode8;
        List<TreeNode> treeNodes = floorLevelTree(treeNode5);
        for (TreeNode treeNode : treeNodes) {
            System.out.print(treeNode.val+" ");
        }
        System.out.println();
    }


    public static List<TreeNode> floorLevelTree( TreeNode root) {
        List<TreeNode> list = new ArrayList();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode poll = queue.poll();
            list.add(poll);
            if (poll.left !=null){
                queue.offer(poll.left);
            }
            if (poll.right != null){
                queue.offer(poll.right);
            }
        }
        return list;
    }
}
